package com.vfa.vocaburay;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import com.vfa.data.Category;
import com.vfa.data.CategoryData;
import com.vfa.data.DataHelper;
import com.vfa.data.Language;
import com.vfa.data.LanguageData;
import com.vfa.data.toastMaking;

public class InputWord extends Activity  {
    /** Called when the activity is first created. */
	private static final int DIALOG_ADD_CATAGORY =1;
	private static final int DIALOG_ADD_LANGUAGE =2;
    private Button btSaveInputWord;
    private Button btCancel;
    private Button btAddCategory;
    private Button btAddLanguage;
    private EditText wordEdt;
    private EditText meanEdt;
    private EditText exampleEdt;
    private EditText readEdt;
    Typeface font;
    private Spinner speechSpinner;
    private Spinner languageSpinner;
    //
    private CategoryData category;
    private LanguageData languageData;
    
    private ArrayList<Category> arrCategoryName = new ArrayList<Category>();
    //private ArrayList<String>arrCategoryName = new ArrayList<String>();
    private ArrayList<Language> arrLanguage = new ArrayList<Language>();
    
    public  Cursor cMake;
    public static final int MAX_LENGHT = 10;
   // private ArrayList categoryInit  = new ArrayList (MAX_LENGHT);
    private ArrayAdapter<Category> speechAdapter;
    private ArrayAdapter<Language> languageAdapter;
//	WordData word;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.e("LocNNT", "InputWord   Activity");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inputwordslayout);
        btSaveInputWord = (Button) findViewById(R.id.btSaveInputWord);
        btCancel = (Button) findViewById(R.id.btCancelInputWord);
        wordEdt = (EditText) findViewById(R.id.wordContent);
        meanEdt = (EditText) findViewById(R.id.wordMeaning);
        exampleEdt = (EditText) findViewById(R.id.wordExample);
        readEdt = (EditText) findViewById(R.id.etWordRead);
        font = Typeface.createFromAsset(getAssets(), "ariali.ttf");  
        readEdt.setTypeface(font);
        initCategoryAndLanguage();
        getAllCategory();
        getAllLanguage();
        
    //	vfaMain.wordData = new WordData(this);
        speechSpinner = (Spinner) findViewById(R.id.CatagorySpinner);
        speechAdapter = new ArrayAdapter<Category>(this, android.R.layout.simple_spinner_item, arrCategoryName);
        //ArrayAdapter<String> speechAdapter = new ArrayAdapter<String>(this, R.layout.listiterm, categoryInit);
        speechAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        speechSpinner.setVisibility(1);
        speechSpinner.setAdapter(speechAdapter);
        
        languageSpinner = (Spinner) findViewById(R.id.LanguageSpinner);
        languageAdapter = new ArrayAdapter<Language>(this, android.R.layout.simple_spinner_item, arrLanguage);
        languageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        languageSpinner.setVisibility(1);
        languageSpinner.setAdapter(languageAdapter);

        btSaveInputWord.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (wordEdt.getText().toString().equals("")
                        || meanEdt.getText().toString().equals("")) {
                    toastMaking.errorToast(getApplicationContext(),
                            "Fill wordname and its meaning").show();
                } else {
                	
                    if ( vfaMain.wordData.checkInDatabase(wordEdt.toString()) == 1) {
                        toastMaking.errorToast(getApplicationContext(),
                                "This word exsited").show();
                    } else { // successfully adding
                        int result  = vfaMain.wordData.insert(wordEdt.getText().toString(), ((Category)speechSpinner
                                .getSelectedItem()).getCategoryID(), ((Language)languageSpinner
                                .getSelectedItem()).getLanguageID(), meanEdt
                                .getText().toString(), exampleEdt.getText()
                                .toString(), readEdt.getText().toString());
                        if(result!=-1)
                        {
                        	setResult(RESULT_OK);
                        	
                        	Toast.makeText(getBaseContext(), "Insert "+ wordEdt.getText()+"  successful!", Toast.LENGTH_SHORT).show();
                        	InputWord.this.finish();
                        }
                        else
                        {
                        	setResult(RESULT_CANCELED);
                        	Toast.makeText(getBaseContext(), "Inserted  failed!", Toast.LENGTH_SHORT).show();
                        }
                        // call dialog
                        //newWordDialog();
                    }
                }

            }
        });

        btCancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                //Intent intent = new Intent(InputWord.this, WordList.class);
                //startActivity(intent);
            	setResult(RESULT_CANCELED);
                InputWord.this.finish();
                }
        });
        btAddCategory = (Button) findViewById(R.id.btAddCategory);
        btAddCategory.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(DIALOG_ADD_CATAGORY);
				
			}
		});
        btAddLanguage = (Button) findViewById(R.id.btAddLanguage);
        btAddLanguage.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(DIALOG_ADD_LANGUAGE);
			}
		});
        Log.e("LocNNT", "ham onCreate chay toi day ha ta ================================");
      //  getAllCategory();

    }

    
    @Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
    	switch (id) {
    	case DIALOG_ADD_CATAGORY:
            // This example shows how to add a custom layout to an AlertDialog
            LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(R.layout.inputcategory, null);
            return new AlertDialog.Builder(InputWord.this)
                   .setTitle("Input new category")
                .setView(textEntryView)
                .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	EditText etNewCategory = (EditText) textEntryView.findViewById(R.id.etNewCategory);
                    	String strNewCategory =  etNewCategory.getText().toString();
                        // them catalog
                    	if(strNewCategory != "")
                    	{
                    		int rs = category.insert(strNewCategory);
                    		if(rs >= 0)
                    		{
                    			refreshCateogry();
                    			Toast.makeText(getBaseContext(), "Inserted category successful!", Toast.LENGTH_SHORT).show();
                    			
                    		}
                    		else{
                    			if(rs == -1)
                    				Toast.makeText(getBaseContext(), "Inserted Category Failed :(!", Toast.LENGTH_SHORT).show();
                    			else{
                    				Toast.makeText(getBaseContext(), "Category "+strNewCategory+ " has existed", Toast.LENGTH_SHORT).show();
                    			}
                    			
                    		}
                    	}
                    	else
                    	{
                    		Toast.makeText(getBaseContext(), "Please input value!", Toast.LENGTH_SHORT).show();
                    	}
                    	
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();
    	case DIALOG_ADD_LANGUAGE:
            // This example shows how to add a custom layout to an AlertDialog
            LayoutInflater factory1 = LayoutInflater.from(this);
            final View textEntryView1 = factory1.inflate(R.layout.inputcategory, null);
            return new AlertDialog.Builder(InputWord.this)
                   .setTitle("Input new language")
                .setView(textEntryView1)
                .setPositiveButton("Add", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    	EditText etNewCategory = (EditText) textEntryView1.findViewById(R.id.etNewCategory);
                    	String strNewLanguage =  etNewCategory.getText().toString();
                        // them catalog
                    	if(strNewLanguage != "")
                    	{
                    		int rs = languageData.insert(strNewLanguage);
                    		if(rs >= 0)
                    		{
                    			refreshLanguage();
                    			Toast.makeText(getBaseContext(), "Inserted language successful!", Toast.LENGTH_SHORT).show();
                    			
                    		}
                    		else{
                    			if(rs == -1)
                    				Toast.makeText(getBaseContext(), "Inserted language Failed :(!", Toast.LENGTH_SHORT).show();
                    			else{
                    				Toast.makeText(getBaseContext(), "Language "+strNewLanguage+ " has existed", Toast.LENGTH_SHORT).show();
                    			}
                    		}
                    	}
                    	else
                    	{
                    		Toast.makeText(getBaseContext(), "Please input value!", Toast.LENGTH_SHORT).show();
                    	}
                    	
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {

                        /* User clicked cancel so do some stuff */
                    }
                })
                .create();
            

    	}
    	return null;
	}

	private void refreshCateogry()
	{
		getAllCategory();
		speechAdapter = new ArrayAdapter<Category>(this,  android.R.layout.simple_spinner_item, arrCategoryName);
		speechAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		//
		
		speechAdapter.notifyDataSetChanged();
		speechSpinner.setAdapter(speechAdapter);
	}
	private void refreshLanguage()
	{
		
		getAllLanguage();
		//languageAdapter.notifyDataSetChanged();
		languageAdapter = new ArrayAdapter<Language>(this, android.R.layout.simple_spinner_item, arrLanguage);
		languageAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		//languageAdapter.notifyDataSetChanged();
		languageSpinner.setAdapter(languageAdapter);
	}
	private void newWordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Add new word successful.");
        builder.setMessage("Do you add more words ?").setCancelable(false)
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                wordEdt.setText("");
                                meanEdt.setText("");
                                exampleEdt.setText("");
                            }
                        }).setNegativeButton("No",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                                Intent intent = new Intent(InputWord.this,
                                        WordList.class);
                                startActivity(intent);
                                InputWord.this.finish();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private void getAllCategory(){
    	arrCategoryName = category.getDatabase();
        System.out.println(arrCategoryName.size());
    }
    private void getAllLanguage(){
       	
    	arrLanguage.clear();
    	
    	arrLanguage = languageData.getAllLangguage();

    }
    private void initCategoryAndLanguage(){
        category =  new CategoryData(getApplicationContext());
        languageData = new LanguageData(getApplicationContext());
    }
}